package com.cory.utils.security;

import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.cory.utils.lang.ExceptionUtils;
 
 
/**
 * DES安全编码组件
 */
public abstract class DESCoder {
    /**
     * ALGORITHM 算法 <br>
     * 可替换为以下任意一种算法，同时key值的size相应改变。
     * 
     * <pre>
     * DES                  key size must be equal to 56
     * DESede(TripleDES)    key size must be equal to 112 or 168
     * AES                  key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
     * Blowfish          	key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
     * RC2                  key size must be between 40 and 1024 bits
     * RC4(ARCFOUR)      	key size must be between 40 and 1024 bits
     * </pre>
     */
    public static final String ALGORITHM = "AES";
    
    public static final int DEFAULT_KEYSIZE = 128;
 
    /**
     * 解密
     * 
     * @param data
     * @param key
     * @return
     */
    public static byte[] decrypt(byte[] data, byte[] key) {
    	try{
    		SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
	 
	        Cipher cipher = Cipher.getInstance(ALGORITHM);
	        cipher.init(Cipher.DECRYPT_MODE, secretKey);
	 
	        return cipher.doFinal(data);
    	} catch (GeneralSecurityException e) {
			throw ExceptionUtils.unchecked(e);
		}
    }
 
    /**
     * 加密
     * 
     * @param data
     * @param key
     * @return
     */
    public static byte[] encrypt(byte[] data, byte[] key) {
    	try{
    		SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
    		
	        Cipher cipher = Cipher.getInstance(ALGORITHM);
	        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
	 
	        return cipher.doFinal(data);
    	} catch (GeneralSecurityException e) {
			throw ExceptionUtils.unchecked(e);
		}
    }
 
    /**
     * 生成密钥
     * 
     * @param seed
     * @return
     */
    public static byte[] initKey() {
    	try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
			keyGenerator.init(DEFAULT_KEYSIZE);
			SecretKey secretKey = keyGenerator.generateKey();
			
			return secretKey.getEncoded();
		} catch (GeneralSecurityException e) {
			throw ExceptionUtils.unchecked(e);
		}
    }
    
}